#!/usr/bin/python
# -*- coding: utf-8 -*-
# vim: set fileencoding=utf-8

import sqlite3
import fileinput
import sys, os, getopt

DB_FILE='dpedia.db.sqlite'
INPUT_FILE=''
SPECIFIED_CULTURE=''

def usage(pg_name):
    print("""
    example: %s -i list.txt -o draft.sqlite

    -h    print this message
    -i    input list file
    -o    db file (append to db if already exist)
    """ % pg_name)

def collect():
    global DB_FILE, INPUT_FILE, SPECIFIED_CULTURE
    print(INPUT_FILE, DB_FILE, SPECIFIED_CULTURE)
    conn = sqlite3.connect(DB_FILE)
    conn.row_factory = sqlite3.Row
    cur = conn.cursor()
    for line in fileinput.input(INPUT_FILE):
        line = line.replace('\'', '_')
        title = ''#line.strip()
        id = ''#line.strip()
        #id = id.replace(' ', '_')
        culture = ''
        alias = ''
        index_alias = line.find('/')
        index_cul = line.find('(')
        if index_cul == -1:
            index_cul = len(line)
        if index_alias == -1:
            index_alias = index_cul
        title = line[:index_alias]
        title.strip()
        id = title.strip()
        id = id.replace(' ', '_')
        alias = line[index_alias:index_cul].strip()
        culture = line[index_cul:].strip()[1:-1]
        print(id,title,culture,alias)
        sql = """insert into pedia (id,title,culture,alias,region,age,resume,data,relations,reference) values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s') 
        """ % (id,title,culture,alias,'','','','','','')
        try:
            cur.execute(sql)
        except:
            print('sql error')
    conn.commit()
    cur.close()

def main(argv):
    global DB_FILE, INPUT_FILE, SPECIFIED_CULTURE
    if len(argv) < 2:
        usage(argv[0])
        sys.exit(2)
    INPUT_FILE = argv[1]
    #SPECIFIED_CULTURE = argv[2]
    #DB_FILE = argv[3]
    collect()


if __name__ == '__main__':
    main(sys.argv[:])

